
import asyncio
import schedule
import time
from datetime import datetime
from services.article_generator import ArticleGenerator
from config.config import Config
import logging

# 设置日志
logging.basicConfig(
    level=getattr(logging, Config.LOG_LEVEL),
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(Config.LOG_FILE),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class ArticleScheduler:
    def __init__(self):
        self.generator = ArticleGenerator()
        self.config = Config()
    
    def job_generate_articles(self):
        """定时生成文章的作业"""
        try:
            logger.info("开始生成每日文章...")
            articles = self.generator.generate_daily_articles(self.config.DAILY_ARTICLE_COUNT)
            article_ids = self.generator.save_articles_to_db(articles)
            logger.info(f"成功生成 {len(articles)} 篇文章，ID: {article_ids}")
        except Exception as e:
            logger.error(f"生成文章失败: {str(e)}")
    
    def run_schedule(self):
        """运行定时任务"""
        # 设置定时任务
        for time_str in self.config.SCHEDULE_TIMES:
            schedule.every().day.at(time_str.strip()).do(self.job_generate_articles)
            logger.info(f"已设置 {time_str} 的定时任务")
        
        logger.info("定时任务已启动")
        
        while True:
            schedule.run_pending()
            time.sleep(60)  # 每分钟检查一次

def run_scheduler():
    """运行调度器"""
    scheduler = ArticleScheduler()
    scheduler.run_schedule()

if __name__ == "__main__":
    run_scheduler()
